﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Xml;

namespace wheel.Services
{
    public class PearsonLongmanDictionaryService
    {
        public static WordDetails GetRandomWord()
        {
            WordDetails ret = null;
            int i = 20;
            while (i > 0 && (ret == null || ret.Definition == null || ret.Definition.Split(new char[]{' '}).Length < 2))
            {
                i--;
                var req = (HttpWebRequest)HttpWebRequest.Create(string.Format("https://api.pearson.com/longman/dictionary/entry/random.xml?apikey={0}", System.Configuration.ConfigurationManager.AppSettings["LongmanDictionaryKey"]));
                var resp = (HttpWebResponse)req.GetResponse();
                XmlDocument doc = new XmlDocument();
                doc.Load(resp.GetResponseStream());
                ret = new WordDetails(doc);
            }
            return ret;
        }

 
    }

    public class WordDetails
    {
        public const int MaxSentenceLength = 100;
        public const int MaxWords = 4;
        public const int MinWords = 1;

        public WordDetails() { }
        public WordDetails(XmlDocument doc)
        {
            id = doc.SelectSingleNode("/Entry").Attributes["id"].Value;
            Text = doc.SelectSingleNode("/Entry/Head/HWD").InnerText.Replace(",","").Replace(".","");
            foreach (XmlNode node in doc.SelectNodes("/Entry/Sense/DEF"))
            {
                if (node.InnerText.Length > MaxSentenceLength)
                    continue;
                string[] tmp = node.InnerText.Replace(",", "").Replace(".", "").Split(new char[] { ' ' });
                Definition= Text;
                Hint = string.Join(" ", tmp).Replace(",", "").Replace(".", "");
                if (MinWords < tmp.Length && tmp.Length < MaxWords)
                {
                    Definition = Hint;
                    Hint = Text;
                    break;
                }
                else
                    continue;

            }
        }
        public string id { get; set; }
        public string Text { get; set; }
        public string Definition { get; set; }
        public string Hint { get; set; }
    }
}